import numpy as np
import sys
import os

def writeFile(fname,block):
    if isjpg(block):
        fname = fname.replace(".bin",".jpg")
    if iseml(block):
        fname = fname.replace(".bin",".eml")
    with open(fname,'wb') as f:
        f.write(block)

def iseml(block):
    try:
        s = bytes.decode(block,"utf-8")
        return s.startswith("From:")
    except:
        return False
def isjpg(block):
    return block[0] == 0xff and block[1] == 0xd8

def hasNoZero(b):
    for i in b:
        if b[i] !=0 :
            return True
    return False

def zeroOfEndBlock(b):
    i = len(b)-1
    n = 0
    while i>=0:
        if b[i] == 0:
            n=n+1
        else:
            break
        i=i-1
    return n

def scan(fname):
    f = open(fname,'rb')
    idx = 0
    block_idx = 0
    block = None
    while True:
        ba = f.read(512)
        if len(ba )  == 0:
            break
        if hasNoZero(ba):
            print("\n[%06d ] %02x" %(idx,ba[0]))
            if block is None:
                block = ba
            else:
                n = zeroOfEndBlock(ba)
                if n < 10: # 
                    block += ba
                else: # is end 
                    block += ba[:(len(ba)-n)]
                    blockFile = 'out/%04d_%08d.bin' %(block_idx,idx)
                    writeFile(blockFile, block)
                    block_idx+=1
                    block = None
        else:
            if block is not None:
                print("write file : " , block_idx)
                blockFile = 'out/%04d_%08d.bin' %(block_idx,idx)
                
                writeFile(blockFile, block)
                block_idx+=1
            block = None    
        #else:
        #    print(".", end='')
        idx+=1
    f.close()
    

scan('cu.img')
